package com.itheima.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

/**
 * 通知,增强的代码
 */
public class TxAdvice1 {
    public DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Object tx(ProceedingJoinPoint pjp) throws Throwable {
        //创建事务管理器对象
        DataSourceTransactionManager dstm = new DataSourceTransactionManager();
        //注入数据源
        dstm.setDataSource(dataSource);
        //获取事务定义对象
        TransactionDefinition td = new DefaultTransactionDefinition();

        //获取事务状态对象
        TransactionStatus transaction = dstm.getTransaction(td);

        Object obj = pjp.proceed(pjp.getArgs());

        dstm.commit(transaction);

        return obj;
    }

}
